import { world, BlockVolume, PistonActivateAfterEvent, Player } from "@minecraft/server"
import {
    generatePlotKey,
    preprocessPlotData,
    isPlotOwnerOrOp
} from "../core/land"

import {
    convertToPlotCoordinates,
    is_in_rect_area
} from '../utils/Land'

/**
* @param { PistonActivateAfterEvent } event
*/
function piston_intercept(event) {
    const plot = is_in_rect_area(event.block.x, event.block.z)

    if (plot) return;

    const volume = new BlockVolume(
        { x: event.block.x, y: event.block.y, z: event.block.z },
        { x: event.block.x, y: event.block.y, z: event.block.z }
    )

    world.getDimension("overworld").fillBlocks(volume, "air")
}

/**
* @param {any} event
* @param {Player} player
* @param {number} x
* @param {number} z
*/
function operational_interception(event, player, x, z) {
    if (player.hasTag("op")) return;

    if (!is_in_rect_area(x, z)) {
        event.cancel = true;
        player.sendMessage("你没有权限执行此操作");
        return
    };;

    const plotMap = preprocessPlotData();
    if (!plotMap) return;

    const plotCoord = convertToPlotCoordinates(x, z);
    const plotKey = generatePlotKey(plotCoord);
    const plot = plotMap.get(plotKey);

    if (!plot) {
        event.cancel = true;
        player.sendMessage("你没有权限执行此操作");
        return
    };

    // 检查权限
    if (!isPlotOwnerOrOp(player, plot.admin)) {
        event.cancel = true;
        player.sendMessage("你没有权限执行此操作");
    }
}

export {
    piston_intercept,
    operational_interception
}